Dropdowns in Selenium
Dropdowns are one of the most commonly used web elements in web applications. They allow users to select one option from a predefined list of values or, in some cases, select multiple options. In Selenium WebDriver, dropdowns can be automated using different techniques depending on whether the dropdown is a standard HTML <select> element, a custom dropdown, a searchable dropdown, an autocomplete component, or a dynamically generated list.
These notes provide a detailed understanding of dropdown handling in Selenium WebDriver using Java, including locating dropdowns, selecting options, validating selections, handling dynamic dropdowns, custom dropdowns, multi-select dropdowns, searchable dropdowns, waits, JavaScript techniques, exceptions, Page Object Model, TestNG, reusable utilities, real-world scenarios, best practices, and interview questions.
For structured Selenium automation learning, you can explore the JustAcademy's Selenium Training Course and use the Register for Course Demo option for course-related information.
1. What is a Dropdown?
A dropdown is a user-interface component that displays a list of available options when the user interacts with it. Instead of displaying all options permanently, a dropdown saves screen space and allows the user to select a required value.
Examples of dropdowns include:
- Country selection
- State selection
- City selection
- Gender selection
- Category selection
- Payment method selection
- Language selection
- Month and year selection
- Product category selection
- Account type selection
2. Dropdowns in Selenium Automation
In Selenium automation, dropdown handling depends on the HTML implementation of the dropdown.
| Dropdown Type | Common HTML Structure | Recommended Selenium Approach |
| Standard Dropdown | <select> | Select class |
| Custom Dropdown | <div>, <li>, buttons | Normal Selenium locators and clicks |
| Searchable Dropdown | Input + list | Send keys and select option |
| Autocomplete | Input + dynamic suggestions | Wait and select suggestion |
| Multi-Select | <select multiple> | Select class |
| Dynamic Dropdown | Options generated dynamically | Explicit waits and dynamic locators |
3. Basic HTML Dropdown
A standard HTML dropdown is generally created using the <select> element and multiple <option> elements.
<select id="country">
<option value="india">India</option>
<option value="usa">United States</option>
<option value="uk">United Kingdom</option>
<option value="canada">Canada</option>
</select>
Here, <select> represents the dropdown and each <option> represents an available value.
4. Understanding the Option Element
Each dropdown option generally contains visible text and a value attribute.
<option value="india">India</option>
| Part | Meaning |
option | Defines an item inside the dropdown |
value="india" | Internal value of the option |
| India | Visible text displayed to the user |
5. Setting Up Selenium
A basic Selenium Java project requires Selenium WebDriver and a browser driver or Selenium Manager-supported browser setup.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DropdownExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
}
}
6. Locating a Dropdown Using ID
If the dropdown has a unique id, the ID locator is usually a simple way to locate it.
WebElement country = driver.findElement(By.id("country"));
7. Locating a Dropdown Using Name
The name attribute can also be used to locate a dropdown.
WebElement country = driver.findElement(By.name("country"));
8. Locating a Dropdown Using Class Name
If a suitable unique class name exists, Selenium can locate the dropdown using className().
WebElement country = driver.findElement(By.className("country-select"));
Avoid using class names that are generated dynamically or shared by many unrelated elements.
9. Locating a Dropdown Using Tag Name
A standard dropdown uses the select HTML tag.
WebElement dropdown = driver.findElement(By.tagName("select"));
Tag name should normally be combined with another strategy when a page contains multiple dropdowns.
10. Locating a Dropdown Using CSS Selector
CSS selectors provide flexible ways to locate dropdowns.
WebElement dropdown = driver.findElement(By.cssSelector("#country"));
Another example:
WebElement dropdown = driver.findElement(By.cssSelector("select[name='country']"));
11. CSS Selector Using Attribute
WebElement dropdown = driver.findElement(
By.cssSelector("select[id='country']")
);
12. CSS Selector Using Multiple Attributes
WebElement dropdown = driver.findElement(
By.cssSelector("select[name='country'][id='country']")
);
13. Locating Dropdown Using XPath
XPath is commonly used when the dropdown does not have a simple unique ID or when a relationship with other elements is required.
WebElement dropdown = driver.findElement(
By.xpath("//select[@id='country']")
);
14. XPath Using Name
WebElement dropdown = driver.findElement(
By.xpath("//select[@name='country']")
);
15. XPath Using Multiple Attributes
WebElement dropdown = driver.findElement(
By.xpath("//select[@id='country' and @name='country']")
);
16. XPath Using Parent and Child Relationship
WebElement dropdown = driver.findElement(
By.xpath("//div[@class='country-container']//select")
);
17. What is the Select Class?
Selenium provides the Select class for handling standard HTML dropdowns created using the <select> element.
import org.openqa.selenium.support.ui.Select;
The basic syntax is:
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
18. selectByVisibleText()
The selectByVisibleText() method selects an option according to the text visible to the user.
Select select = new Select(driver.findElement(By.id("country")));
select.selectByVisibleText("India");
This is useful when the displayed option text is stable and known.
19. selectByValue()
The selectByValue() method selects an option using its HTML value attribute.
Select select = new Select(driver.findElement(By.id("country")));
select.selectByValue("india");
For this HTML:
<option value="india">India</option>
the Selenium statement is:
select.selectByValue("india");
20. selectByIndex()
The selectByIndex() method selects an option using its numerical position.
Select select = new Select(driver.findElement(By.id("country")));
select.selectByIndex(0);
Indexes normally start from 0.
| Index | Option |
| 0 | India |
| 1 | United States |
| 2 | United Kingdom |
Index-based selection should be used carefully because adding or removing options can change the indexes.
21. Complete Select Example
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
public class DropdownTest {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
driver.quit();
}
}
22. Get All Dropdown Options
The getOptions() method returns all options present in a standard dropdown.
Select select = new Select(driver.findElement(By.id("country")));
List<WebElement> options = select.getOptions();
Import the List class:
import java.util.List;
23. Print All Dropdown Options
Select select = new Select(driver.findElement(By.id("country")));
List<WebElement> options = select.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
}
24. Count Dropdown Options
Select select = new Select(driver.findElement(By.id("country")));
List<WebElement> options = select.getOptions();
System.out.println("Total options: " + options.size());
25. Get Selected Option
The getFirstSelectedOption() method returns the currently selected option.
Select select = new Select(driver.findElement(By.id("country")));
WebElement selected = select.getFirstSelectedOption();
System.out.println(selected.getText());
26. Verify Selected Option
Select select = new Select(driver.findElement(By.id("country")));
select.selectByVisibleText("India");
String selectedText = select
.getFirstSelectedOption()
.getText();
if (selectedText.equals("India")) {
System.out.println("Correct option selected");
}
27. Check Whether Dropdown Supports Multiple Selection
The isMultiple() method determines whether the dropdown allows multiple selections.
Select select = new Select(driver.findElement(By.id("skills")));
if (select.isMultiple()) {
System.out.println("Multiple selection supported");
} else {
System.out.println("Single selection dropdown");
}
28. Multi-Select Dropdown
A multi-select dropdown may use the multiple attribute.
<select id="skills" multiple>
<option value="java">Java</option>
<option value="selenium">Selenium</option>
<option value="sql">SQL</option>
<option value="python">Python</option>
</select>
29. Selecting Multiple Options
Select skills = new Select(
driver.findElement(By.id("skills"))
);
skills.selectByVisibleText("Java");
skills.selectByVisibleText("Selenium");
skills.selectByVisibleText("SQL");
30. Deselect All Options
For a multi-select dropdown, deselectAll() removes all selected options.
Select skills = new Select(
driver.findElement(By.id("skills"))
);
skills.deselectAll();
31. Deselect by Visible Text
skills.deselectByVisibleText("Java");
32. Deselect by Value
skills.deselectByValue("java");
33. Deselect by Index
skills.deselectByIndex(0);
34. Get All Selected Options
List<WebElement> selectedOptions =
skills.getAllSelectedOptions();
for (WebElement option : selectedOptions) {
System.out.println(option.getText());
}
35. Validate Number of Selected Options
List<WebElement> selectedOptions =
skills.getAllSelectedOptions();
if (selectedOptions.size() == 3) {
System.out.println("Three options are selected");
}
36. Selecting an Option Dynamically
Sometimes the option to be selected is stored in a variable.
String countryName = "India";
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText(countryName);
This technique is useful for data-driven automation.
37. Selecting Based on User Test Data
String expectedCountry = "Canada";
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText(expectedCountry);
38. Selecting an Option Using a Loop
Select country = new Select(
driver.findElement(By.id("country"))
);
List<WebElement> options = country.getOptions();
for (WebElement option : options) {
if (option.getText().equals("India")) {
option.click();
break;
}
}
39. Finding an Option Without Select Class
For a standard dropdown, Selenium's Select class is preferred. However, an option can also be located directly.
driver.findElement(
By.xpath("//select[@id='country']//option[text()='India']")
).click();
40. Custom Dropdown
Not every dropdown uses the HTML <select> element. Modern applications frequently create custom dropdowns using <div>, <button>, <ul>, and <li>.
<div class="dropdown">
<button>Select Country</button>
<ul>
<li>India</li>
<li>Canada</li>
<li>Australia</li>
</ul>
</div>
The Selenium Select class should not be used for this type of dropdown because it is not a real HTML <select> element.
41. Handling Custom Dropdown
driver.findElement(
By.xpath("//button[text()='Select Country']")
).click();
driver.findElement(
By.xpath("//li[text()='India']")
).click();
42. Custom Dropdown Using CSS
driver.findElement(
By.cssSelector(".country-dropdown")
).click();
driver.findElement(
By.cssSelector(".country-option[data-value='india']")
).click();
43. Searchable Dropdown
A searchable dropdown contains an input field that allows users to type and filter options.
<input id="countrySearch" placeholder="Search country">
Selenium can enter the required text and select the matching suggestion.
WebElement search = driver.findElement(
By.id("countrySearch")
);
search.sendKeys("India");
44. Selecting Search Result
driver.findElement(
By.xpath("//li[contains(text(),'India')]")
).click();
45. Autocomplete Dropdown
Autocomplete dropdowns dynamically display suggestions based on user input.
driver.findElement(By.id("city"))
.sendKeys("Mum");
driver.findElement(
By.xpath("//li[contains(text(),'Mumbai')]")
).click();
46. Dynamic Dropdown
Dynamic dropdown options may appear after an API request or after another element is selected.
For example:
- Select Country.
- Application loads states.
- Select State.
- Application loads cities.
- Select City.
47. Dependent Dropdown
A dependent dropdown changes its options according to another dropdown.
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
Select state = new Select(
driver.findElement(By.id("state"))
);
state.selectByVisibleText("Maharashtra");
48. Handling Dynamic Options with Explicit Wait
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement option = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//option[text()='Maharashtra']")
)
);
option.click();
49. Waiting for Custom Dropdown Option
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
driver.findElement(By.id("country")).click();
WebElement option = wait.until(
ExpectedConditions.elementToBeClickable(
By.xpath("//li[text()='India']")
)
);
option.click();
50. Explicit Wait for Dropdown Visibility
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement dropdown = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("country")
)
);
dropdown.click();
51. Explicit Wait for Clickability
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement dropdown = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("country")
)
);
dropdown.click();
52. Implicit Wait
An implicit wait tells Selenium to wait for a specified amount of time when locating elements.
driver.manage().timeouts().implicitlyWait(
Duration.ofSeconds(10)
);
Implicit waits apply broadly to element searches, whereas explicit waits provide more targeted synchronization.
53. Explicit Wait vs Implicit Wait
| Feature | Implicit Wait | Explicit Wait |
| Scope | General element searches | Specific condition |
| Control | Lower | Higher |
| Dynamic dropdowns | Less precise | More suitable |
| Condition | Element presence | Visibility, clickability, presence, etc. |
54. JavaScript Click for Dropdown
JavaScript can sometimes be used when a normal Selenium click is blocked by application-specific UI behavior.
WebElement dropdown = driver.findElement(
By.id("country")
);
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].click();",
dropdown
);
55. JavaScript for Selecting an Option
JavaScript can directly manipulate a select element when necessary, although normal Selenium interaction should generally be preferred.
JavascriptExecutor js =
(JavascriptExecutor) driver;
js.executeScript(
"arguments[0].value='india';",
dropdown
);
After manipulating the DOM directly, the application may also require its associated change event to be triggered. Therefore, JavaScript should not be the default approach.
56. When Not to Use JavaScript
- When normal Selenium click works correctly
- When the application requires actual user-like interaction
- When JavaScript bypasses important UI behavior
- When direct DOM manipulation creates unreliable tests
- When the application uses event handlers that are not triggered by the script
57. Standard Dropdown vs Custom Dropdown
| Standard Dropdown | Custom Dropdown |
Uses <select> | Usually uses <div>, <button>, etc. |
Uses Selenium Select | Uses normal WebElement interactions |
| Supports selectByValue() | Does not support Select methods |
| Supports selectByIndex() | Requires custom locator |
| Easy to automate | May require waits and dynamic locators |
58. Registration Form Dropdown
A registration form commonly contains dropdowns such as country, state, city, date of birth, education, and occupation.
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
Select state = new Select(
driver.findElement(By.id("state"))
);
state.selectByVisibleText("Maharashtra");
59. Gender Dropdown
Some applications represent gender selection using a dropdown instead of radio buttons.
Select gender = new Select(
driver.findElement(By.id("gender"))
);
gender.selectByVisibleText("Male");
60. Payment Method Dropdown
Select payment = new Select(
driver.findElement(By.id("paymentMethod"))
);
payment.selectByVisibleText("Credit Card");
61. Delivery Method Dropdown
Select delivery = new Select(
driver.findElement(By.id("delivery"))
);
delivery.selectByVisibleText("Express Delivery");
62. Product Category Dropdown
Select category = new Select(
driver.findElement(By.id("category"))
);
category.selectByVisibleText("Electronics");
63. Country-State-City Flow
Country
|
v
State
|
v
City
|
v
Submit
This type of dependent dropdown flow is frequently automated in registration, address, shopping, and booking applications.
64. Verify Country Selection
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
String actual = country
.getFirstSelectedOption()
.getText();
if (actual.equals("India")) {
System.out.println("Country verified");
}
65. Verify Dropdown Contains an Option
Select country = new Select(
driver.findElement(By.id("country"))
);
boolean found = false;
for (WebElement option : country.getOptions()) {
if (option.getText().equals("India")) {
found = true;
break;
}
}
System.out.println("India available: " + found);
66. Verify Number of Options
Select country = new Select(
driver.findElement(By.id("country"))
);
int count = country.getOptions().size();
System.out.println("Option count: " + count);
67. Verify Default Option
Select country = new Select(
driver.findElement(By.id("country"))
);
String defaultValue = country
.getFirstSelectedOption()
.getText();
System.out.println("Default: " + defaultValue);
68. Placeholder Option
Many dropdowns contain a placeholder such as Select Country.
<option value="">Select Country</option>
<option value="india">India</option>
Automation should verify that the user selects a real option rather than leaving the placeholder selected.
69. Required Dropdown Validation
Select country = new Select(
driver.findElement(By.id("country"))
);
String selected = country
.getFirstSelectedOption()
.getAttribute("value");
if (selected == null || selected.isEmpty()) {
System.out.println("Country is required");
}
70. Dropdown Inside a Table
Tables may contain dropdowns in individual rows.
WebElement row = driver.findElement(
By.xpath("//tr[td[text()='Product A']]")
);
Select status = new Select(
row.findElement(By.tagName("select"))
);
status.selectByVisibleText("Approved");
71. Selecting Dropdown in a Specific Table Row
WebElement row = driver.findElement(
By.xpath("//tr[td[contains(text(),'Order 1001')]]")
);
WebElement dropdown = row.findElement(
By.tagName("select")
);
Select orderStatus = new Select(dropdown);
orderStatus.selectByVisibleText("Shipped");
72. Dropdown in Product Listing
E-commerce applications may contain sorting and filtering dropdowns.
Select sort = new Select(
driver.findElement(By.id("sort"))
);
sort.selectByVisibleText("Price: Low to High");
73. Dropdown in Modal
When a dropdown is inside a modal, first ensure that the modal is visible.
WebElement modal = driver.findElement(
By.id("userModal")
);
WebElement dropdown = modal.findElement(
By.id("country")
);
Select country = new Select(dropdown);
country.selectByVisibleText("India");
74. Dropdown Inside an Iframe
If the dropdown is inside an iframe, Selenium must switch to the iframe before locating the dropdown.
driver.switchTo().frame("paymentFrame");
Select payment = new Select(
driver.findElement(By.id("payment"))
);
payment.selectByVisibleText("Credit Card");
driver.switchTo().defaultContent();
75. Nested Iframe Dropdown
driver.switchTo().frame("outerFrame");
driver.switchTo().frame("innerFrame");
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
driver.switchTo().defaultContent();
76. Dropdown in Shadow DOM
Modern web applications may place dropdown elements inside Shadow DOM.
Selenium provides Shadow DOM support through the WebElement ShadowRoot API in supported versions.
WebElement host = driver.findElement(
By.cssSelector("custom-dropdown")
);
SearchContext shadowRoot = host.getShadowRoot();
WebElement dropdown = shadowRoot.findElement(
By.cssSelector("select")
);
77. Dynamic List Dropdown
A custom dropdown may generate its options only after clicking the main element.
driver.findElement(
By.id("categoryDropdown")
).click();
WebDriverWait wait = new WebDriverWait(
driver,
Duration.ofSeconds(10)
);
WebElement option = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.xpath("//li[text()='Electronics']")
)
);
option.click();
78. Dynamic IDs in Dropdown
Some applications generate dynamic IDs.
WebElement dropdown = driver.findElement(
By.xpath("//select[starts-with(@id,'country_')]")
);
79. Dynamic Class Names
When class names contain dynamic values, use stable attributes whenever possible.
WebElement dropdown = driver.findElement(
By.xpath("//select[contains(@class,'country')]")
);
80. Dropdown Automation Flow
Open Application
|
v
Locate Dropdown
|
v
Identify Dropdown Type
|
+--------------------+
| |
v v
Standard Select Custom Dropdown
| |
v v
Select Class Click + Locate Option
| |
+---------+----------+
|
v
Verify Selection
|
v
Continue Test
|
v
Close Browser
81. Common Dropdown Scenarios
| Scenario | Technique |
| Standard select | Select class |
| Select by text | selectByVisibleText() |
| Select by value | selectByValue() |
| Select by position | selectByIndex() |
| Multiple selection | isMultiple() |
| Get all options | getOptions() |
| Get selected option | getFirstSelectedOption() |
| Custom dropdown | Click and locate option |
| Dynamic dropdown | Explicit wait |
| Searchable dropdown | Input + suggestion selection |
82. Dropdown Validation Checklist
- Verify dropdown is displayed.
- Verify dropdown is enabled.
- Verify dropdown contains expected options.
- Verify default option.
- Select the required option.
- Verify selected option.
- Verify dependent dropdown behavior.
- Verify invalid or empty selection.
- Verify dynamic options.
- Verify multi-select behavior when applicable.
83. Common Mistakes
- Using
Select class for a custom dropdown
- Using unstable dynamic locators
- Using index when the order of options can change
- Not waiting for dynamically loaded options
- Ignoring iframe context
- Ignoring Shadow DOM
- Not validating the final selection
- Using JavaScript unnecessarily
- Using
Thread.sleep() everywhere
84. Bad Dropdown Locator
driver.findElement(
By.xpath("//select[1]")
);
This locator depends only on position and may become unreliable when the page structure changes.
85. Better Dropdown Locator
driver.findElement(
By.id("country")
);
A stable unique ID is generally easier to maintain.
86. Best Practices for Dropdown Automation
- Identify the dropdown type before writing automation code.
- Use the
Select class only for real HTML <select> elements.
- Prefer stable IDs and meaningful attributes.
- Use visible text when business readability is important.
- Use value when the value attribute is stable.
- Avoid unnecessary index-based selection.
- Use explicit waits for dynamic dropdowns.
- Validate the selected option.
- Use reusable dropdown utilities.
- Avoid unnecessary JavaScript.
87. Real-World Registration Scenario
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
Select state = new Select(
driver.findElement(By.id("state"))
);
state.selectByVisibleText("Maharashtra");
Select city = new Select(
driver.findElement(By.id("city"))
);
city.selectByVisibleText("Mumbai");
88. Real-World E-Commerce Scenario
Select category = new Select(
driver.findElement(By.id("category"))
);
category.selectByVisibleText("Electronics");
Select sort = new Select(
driver.findElement(By.id("sort"))
);
sort.selectByVisibleText("Price: Low to High");
89. Real-World Booking Scenario
Select passengers = new Select(
driver.findElement(By.id("passengers"))
);
passengers.selectByVisibleText("2");
90. Real-World Payment Scenario
Select payment = new Select(
driver.findElement(By.id("paymentMethod"))
);
payment.selectByVisibleText("Credit Card");
91. TestNG Dropdown Validation
import org.testng.Assert;
import org.testng.annotations.Test;
@Test
public void verifyCountry() {
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
String actual =
country.getFirstSelectedOption().getText();
Assert.assertEquals(actual, "India");
}
92. Complete TestNG Dropdown Test
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DropdownTest {
WebDriver driver;
@BeforeMethod
public void setup() {
driver = new ChromeDriver();
driver.get("https://example.com");
}
@Test
public void verifyCountryDropdown() {
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText("India");
String selected =
country.getFirstSelectedOption().getText();
Assert.assertEquals(selected, "India");
}
@AfterMethod
public void tearDown() {
driver.quit();
}
}
93. Dropdown Using Page Object Model
In Page Object Model, dropdown locators and interaction methods can be placed inside a page class.
public class RegistrationPage {
WebDriver driver;
By country = By.id("country");
By state = By.id("state");
public RegistrationPage(WebDriver driver) {
this.driver = driver;
}
public void selectCountry(String value) {
Select select =
new Select(driver.findElement(country));
select.selectByVisibleText(value);
}
public void selectState(String value) {
Select select =
new Select(driver.findElement(state));
select.selectByVisibleText(value);
}
}
94. Reusable Dropdown Utility
public class DropdownUtil {
public static void selectByText(
WebDriver driver,
By locator,
String text) {
Select select =
new Select(driver.findElement(locator));
select.selectByVisibleText(text);
}
}
Usage:
DropdownUtil.selectByText(
driver,
By.id("country"),
"India"
);
95. Reusable Select by Value Utility
public static void selectByValue(
WebDriver driver,
By locator,
String value) {
Select select =
new Select(driver.findElement(locator));
select.selectByValue(value);
}
96. Dropdown Utility with Explicit Wait
public static void selectByText(
WebDriver driver,
By locator,
String text) {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(locator)
);
Select select = new Select(element);
select.selectByVisibleText(text);
}
97. Selecting From Multiple Dropdowns
List<WebElement> dropdowns =
driver.findElements(By.tagName("select"));
for (WebElement element : dropdowns) {
Select select = new Select(element);
System.out.println(
select.getFirstSelectedOption().getText()
);
}
98. Finding Selected Option Using CSS
For standard HTML dropdowns, the selected option may have the selected attribute.
WebElement selected = driver.findElement(
By.cssSelector("select#country option:checked")
);
System.out.println(selected.getText());
99. CSS :checked Selector
The :checked pseudo-class can be used for checked or selected form controls where supported by the browser and element type.
WebElement selected = driver.findElement(
By.cssSelector("#country option:checked")
);
100. Verify Dropdown Has a Selection
Select country = new Select(
driver.findElement(By.id("country"))
);
WebElement selected =
country.getFirstSelectedOption();
String text = selected.getText();
if (!text.equals("Select Country")) {
System.out.println("Valid option selected");
}
101. Count Selected Options
Select skills = new Select(
driver.findElement(By.id("skills"))
);
int count =
skills.getAllSelectedOptions().size();
System.out.println(
"Selected options: " + count
);
102. Verify Specific Value
Select country = new Select(
driver.findElement(By.id("country"))
);
String value =
country.getFirstSelectedOption()
.getAttribute("value");
if (value.equals("india")) {
System.out.println("India selected");
}
103. Required Dropdown Group
A required dropdown can be validated before submitting a form.
Select country = new Select(
driver.findElement(By.id("country"))
);
String value =
country.getFirstSelectedOption()
.getAttribute("value");
if (value == null || value.isEmpty()) {
System.out.println(
"Please select a country"
);
}
104. Dropdown Test Case Format
| Test Case | Expected Result |
| Verify dropdown displayed | Dropdown should be visible |
| Verify dropdown enabled | Dropdown should be enabled |
| Verify default option | Expected default should be selected |
| Select valid option | Option should be selected |
| Verify selection | Selected value should match expected value |
| Verify options | Expected options should be available |
| Verify dependent dropdown | Options should update correctly |
| Verify required validation | Validation should appear for empty selection |
105. Dropdown Test Data
Country State City
India Maharashtra Mumbai
India Karnataka Bengaluru
India Delhi New Delhi
Canada Ontario Toronto
USA California Los Angeles
External test data can also be used with TestNG data providers, Excel, CSV, JSON, or other test-data sources.
106. Logging Dropdown Selection
String countryName = "India";
System.out.println(
"Selecting country: " + countryName
);
Select country = new Select(
driver.findElement(By.id("country"))
);
country.selectByVisibleText(countryName);
System.out.println(
"Country selected successfully"
);
107. Assertions for Dropdowns
String actual =
country.getFirstSelectedOption().getText();
Assert.assertEquals(
actual,
"India",
"Country selection is incorrect"
);
108. Testing Dependent Dropdown Behavior
- Select the parent dropdown.
- Wait for child options to load.
- Read available child options.
- Verify the expected options.
- Select the required child option.
- Continue to the next dependent dropdown.
109. Three-Option Dropdown
<select id="plan">
<option value="basic">Basic</option>
<option value="standard">Standard</option>
<option value="premium">Premium</option>
</select>
110. Select Premium Plan
Select plan = new Select(
driver.findElement(By.id("plan"))
);
plan.selectByVisibleText("Premium");
111. Verify Premium Plan
String selectedPlan =
plan.getFirstSelectedOption().getText();
Assert.assertEquals(
selectedPlan,
"Premium"
);
112. Verify Other Options
List<WebElement> options =
plan.getOptions();
for (WebElement option : options) {
if (!option.getText().equals("Premium")) {
System.out.println(
"Other option: " + option.getText()
);
}
}
113. Interview Question: How Do You Handle Dropdowns in Selenium?
For standard HTML dropdowns, Selenium provides the Select class. The dropdown WebElement is passed to the Select constructor, after which methods such as selectByVisibleText(), selectByValue(), and selectByIndex() can be used.
114. Interview Question: What is the Select Class?
The Select class is a Selenium support class used to interact with HTML <select> elements.
115. Interview Question: How Do You Select by Visible Text?
Select select = new Select(
driver.findElement(By.id("country"))
);
select.selectByVisibleText("India");
116. Interview Question: How Do You Select by Value?
select.selectByValue("india");
117. Interview Question: How Do You Select by Index?
select.selectByIndex(0);
118. Interview Question: How Do You Get All Options?
List<WebElement> options =
select.getOptions();
119. Interview Question: How Do You Get the Selected Option?
WebElement selected =
select.getFirstSelectedOption();
120. Interview Question: How Do You Handle a Custom Dropdown?
A custom dropdown does not use the standard HTML <select> element. Therefore, the Selenium Select class should not be used. Instead, locate and click the dropdown and then locate the desired option using appropriate XPath or CSS selectors.
121. Interview Question: What If a Dropdown Is Not Clickable?
Possible causes include an overlay, animation, disabled element, incorrect locator, iframe, or synchronization issue. Use explicit waits, verify the element state, check the browser context, and inspect the page structure.
122. Interview Question: How Do You Handle a Hidden Dropdown?
First determine how the application displays the dropdown. Some dropdowns become visible only after clicking a button. Use the actual user interaction to open the dropdown and then wait for the option to become visible or clickable.
123. Practical Project: Registration Form Automation
Automate a registration page containing:
- Country dropdown
- State dropdown
- City dropdown
- Education dropdown
- Occupation dropdown
Test flow:
- Open registration page.
- Select country.
- Wait for state options.
- Select state.
- Wait for city options.
- Select city.
- Select education.
- Select occupation.
- Validate every selected value.
- Submit the form.
- Verify successful registration.
124. Advanced Project: E-Commerce Dropdown Automation
Create an automation framework for an e-commerce website containing:
- Category dropdown
- Brand filter
- Price sorting dropdown
- Availability filter
- Product quantity dropdown
- Country and delivery location dropdowns
The framework should include:
- Page Object Model
- Reusable dropdown utilities
- Explicit waits
- TestNG assertions
- Data-driven testing
- Logging
- Screenshot capture
- HTML reporting
125. Best-Practice Summary
| Practice | Recommendation |
| Identify type | Determine whether it is standard or custom |
| Standard dropdown | Use Selenium Select |
| Custom dropdown | Use normal WebElement interactions |
| Locator | Prefer stable attributes |
| Selection | Prefer visible text or stable value |
| Index | Use only when option order is stable |
| Dynamic options | Use explicit waits |
| Validation | Verify selected value |
| Framework | Use Page Object Model and reusable utilities |
| JavaScript | Use only when normal Selenium interaction is insufficient |
126. Conclusion
Dropdown handling is an important Selenium WebDriver skill because dropdowns are widely used in registration forms, e-commerce applications, booking systems, payment pages, dashboards, and enterprise web applications. For standard HTML <select> elements, Selenium's Select class provides convenient methods such as selectByVisibleText(), selectByValue(), selectByIndex(), getOptions(), and getFirstSelectedOption().
For custom, searchable, autocomplete, dependent, and dynamic dropdowns, testers must use appropriate locators, explicit waits, WebElement interactions, and application-specific strategies. Reliable dropdown automation should focus on stable locators, synchronization, validation, reusable utilities, and maintainable framework design.
For further Selenium automation learning, explore the JustAcademy's Selenium Training Course.
To register for a course demo, visit the Register for Course Demo page.